import wsgiref.handlers
import os
#from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext import *
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from cgi import parse_qs, escape
from datetime import datetime
from google.appengine.ext import db
import re
import time
import math
import simplejson
import urllib

class Greeting(db.Model):
  author = db.StringProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)
class taTweople(db.Model):
  picurl = db.StringProperty()
  name = db.StringProperty()
  handle= db.StringProperty()
  bio= db.StringProperty()
  follower_count=db.IntegerProperty()
  friend_count=db.IntegerProperty()

class TweetUpDetail(db.Model):
  eventhandle=db.StringProperty()
  description=db.TextProperty()
  location = db.StringProperty()
  date = db.DateTimeProperty()
class TweetUpPeople(db.Model):
  tweetup=db.ReferenceProperty(TweetUpDetail)
  user = db.StringProperty()
  location = db.StringProperty()
  date = db.DateTimeProperty()
class TweetActiveness(db.Model):
  user = db.StringProperty()
  activeindex=db.IntegerProperty()
  date = db.DateTimeProperty(auto_now_add=True)

def get_realtweethtml(data):
    try:
        html="";
        for result in data['results']:
            font_start_tag='<font color="'+ '#000000' + '">';
            user_tag='<a style=\"text-decoration:none\" href=\"http://www.twitter.com/'+result['from_user']+'\">'+result['from_user']+":</a>";
            tweet=result["text"];
            html=html+user_tag+font_start_tag+tweet+"</font><br>";
        return html;
    except:
        return 'Loading...';

########### get_yql ##########
def get_yql(q,format):
    params=locals()
    query_params= urllib.urlencode(params)
    base_url=u'http://query.yahooapis.com/v1/public/yql?'
    myurl = base_url + query_params
    resobject=urlfetch.fetch(myurl);
    if(resobject!=None):
      return resobject.content
    return simplejson.dumps(None);

########### get_yql_json ##########
def get_yql_json(q):
  response=get_yql(q,'json');
  my_object=simplejson.loads(response);
  return my_object;

########### get_profile_image_src ##########
def get_profile_image_src(query):
    try:
        yql_query='select * from html where url="http://twitter.com/'+query+'\" and xpath=\'//img[@id="profile-image"]\'';
        #response=get_yql(yql_query,'json');
        my_object=get_yql_json(yql_query);
        image_url=my_object['query']['results']['img']['src'];
        return image_url;
    except:
        return "http://www.tweetactive.com/images/missing.png";
####### Get users ###########
def getuserlistpage(user,param,page):
  mypass='mypass'
  yql_query='select * from html where url=\"http://tweetactive:'+mypass+'@twitter.com/'+user+'/'+param+'?page='+str(page)+'\" and xpath=\'//span[@class="nickname"]\'';
  myobject=get_yql_json(yql_query);
  if(myobject['query']['count']>0):
    if myobject['query']['results']:
      return myobject['query']['results']['span'];
    else:
      return None
  else:
    return None;
def getfriends(user):
  page=1;
  friendlist=[];
  curlist=getuserlistpage(user,'friends',page);
  while(curlist):
    page=page+1;
    for item in curlist:
      friendlist.append(item['content'])
    curlist=getuserlistpage(user,'friends',page);
  myfriends={};
  myfriends['count']=len(friendlist)
  myfriends['list']=friendlist;
  return myfriends;
def getfollowers(user):
  page=1;
  friendlist=[];
  curlist=getuserlistpage(user,'followers',page);
  while(curlist):
    page=page+1;
    for item in curlist:
      friendlist.append(item['content'])
    curlist=getuserlistpage(user,'friends',page);
  myfriends={};
  myfriends['count']=len(friendlist)
  myfriends['list']=friendlist;
  return myfriends;  

########### getHealth ##########
def getHealth(index):
    cur=index*10
    if(cur==0):
        return 0;
    else:
        return int(10*math.log(cur));

########### timedelta2Mili ##########
def timedelta2Mili(dt):
    """ Convert timedelta object to micriseconds"""
    days = dt.days
    sec = dt.seconds
    micros = dt.microseconds
    daysSec = 24 * 60 * 60 * days
    tdMili = (daysSec + sec) * 1000 + micros/1000
    return tdMili

###########Returns time diff in milli##########
def gettimediff(iso_datetime):
  d1=datetime.now();
  d2 = datetime(*map(int, re.split('[^\d]', iso_datetime)[:-1]));
  #convert=24*60*60*1000;
  d=timedelta2Mili(d1-d2);
  return d;

###########GET THE SPEED##########
def get_speed(count,timediff):
  c1=count*1000*60*60*24;
  return c1/timediff;

def parse_rfcdatetime(rfctime):
  sss=rfctime.split(' ');
  pformat=sss[0]+' '+sss[2]+' '+sss[1]+' '+sss[4]+' '+sss[3];
  pformat=pformat.replace(',','');
  ptime=time.strptime(pformat);
  return datetime(*ptime[0:5])
#### getactiveindex #######################
def getactiveindex(q):
    index=memcache.get('getactiveindex/'+q);
    if index is not None:
        return index;
    index=getHealth(getkeywordrate(q));
    memcache.add('getactiveindex/'+q, index, 1800);
    return index;
def getkeywordjson(query):
    try:
        parsedjson=memcache.get('twittersearch/'+query);
        if parsedjson is not None:
            return parsedjson;
        params={'q':query};
        search_url=u'http://search.twitter.com/search.json?';
        full_url=search_url+urllib.urlencode(params);
        jsonresponse=urlfetch.fetch(full_url);
        parsedjson=simplejson.loads(jsonresponse.content);
        memcache.add('twittersearch/'+query, parsedjson, 5);
        return parsedjson;
    except:
        return None;
def getuserinfojson(query):
    try:
        parsedjson=memcache.get('getuserinfojson/'+query);
        if parsedjson is not None:
            return parsedjson;
        search_url=u'http://twitter.com/users/show/'+query+'.json';
        full_url=search_url;
        jsonresponse=urlfetch.fetch(full_url);
        parsedjson=simplejson.loads(jsonresponse.content);
        memcache.add('getuserinfojson/'+query, parsedjson, 18000);
        return parsedjson;
    except:
        return None;
def gettrendlistjson():
    try:
        parsedjson=memcache.get('twittertrend');
        if parsedjson is not None:
            return parsedjson;
        full_url="http://search.twitter.com/trends.json";
        jsonresponse=urlfetch.fetch(full_url);
        parsedjson=simplejson.loads(jsonresponse.content);
        memcache.add("twittertrend", parsedjson, 1800);
        return parsedjson;
    except:
        return {'trends':[{'name':'twitter','url':'http://www.twitter.com'}]};
def getkeywordrate(q):
    try:
      result_parsed_json=getkeywordjson(q);
      if(not result_parsed_json):
          return random()*100;
      count=len(result_parsed_json['results']);
      date_of_zero=result_parsed_json['results'][0]['created_at'];
      date_max=result_parsed_json['results'][count-1]['created_at'];
      milli=timedelta2Mili(datetime.now()-parse_rfcdatetime(date_max));
      corrected_count=count*24*60*60*1000;
      tweetRate=corrected_count/milli
      return tweetRate;
    except:
        return 0;

###############################################
# GET friends #######################
###############################################
class friends(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html';
    query = self.request.get('q', '')
    json=None
    frndlst=None
    if query:
      frndlst=getfriends(query)
      json=simplejson.dumps(frndlst)
    else:
      frndlst=getfriends('rencyphilip')
      json=simplejson.dumps(frndlst)
    self.response.out.write(json);
###############################################
# GET followers #######################
###############################################
class followers(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html';
    query = self.request.get('q', '')
    json=None
    frndlst=None
    if query:
      frndlst=getfollowers(query)
      json=simplejson.dumps(frndlst)
    else:
      frndlst=getfollowers('markandey')
      json=simplejson.dumps(frndlst)
    self.response.out.write(json);
###############################################
# GET THE PROFILE IMAGE #######################
###############################################
class profileimage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'image/jpeg';
    query = self.request.get('q', '')
    if query:
      self.response.out.write(urlfetch.fetch(get_profile_image_src(query)).content);
    else:
      self.response.out.write(urlfetch.fetch(get_profile_image_src('markandey')).content);
###############################################
# getactivity #######################
###############################################    
class getactivity(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html';
    query = self.request.get('q', '')
    callback = self.request.get('callback', '')
    if query and callback:
        params={};
        params['index']=getactiveindex(query);
        params['pic']=get_profile_image_src(query);
        params['user']=query;
        jsonstr=callback+'('+simplejson.dumps(params)+')';
        self.response.out.write(jsonstr);
    elif query:
        params={};
        params['index']=getactiveindex(query);
        params['pic']=get_profile_image_src(query);
        params['user']=query;
        jsonstr=simplejson.dumps(params);
        self.response.out.write(jsonstr);
    else:
		self.response.out.write('error');
###############################################
# gettwitterlove #######################
###############################################    
class gettwitterlove(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html';
    queries = self.request.get('q', '')
    query_array=queries.split(',');
    Result=[];
    callback = self.request.get('callback', '')
    if queries and callback:
      for query in query_array:
        params={};
        params['index']=(getkeywordrate('love+'+query)-getkeywordrate('hate+'+query));
        params['query']=query;
        Result.append(params);
      jsonstr=callback+'('+simplejson.dumps(Result)+')';
      self.response.out.write(jsonstr);
    else:
      self.response.out.write('error');

###############################################
# getkeywordactivity #######################
###############################################    
class getkeywordactivity(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html';
    self.response.headers.add_header("Pragma", "no-cache");
    self.response.headers.add_header("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store");
    queries = self.request.get('q', '')
    query_array=queries.split(',');
    Result=[];
    callback = self.request.get('callback', '')
    if queries and callback:
      for query in query_array:
        params={};
        params['index']=getkeywordrate(query);
        params['query']=query;
        Result.append(params);
      jsonstr=callback+'('+simplejson.dumps(Result)+')';
      self.response.out.write(jsonstr);
    else:
      self.response.out.write('error');
      
###############################################
# MainPage #######################
###############################################
class MainPage(webapp.RequestHandler):
  def get(self):
    template_values = {
      
      }

    path = os.path.join(os.path.dirname(__file__), 'newhome.html')
    self.response.out.write(template.render(path, template_values))
###############################################
# keywordactive #######################
###############################################
class keywordactive(webapp.RequestHandler):
  def get(self):
    template_values = {
      
      }
    
    path = os.path.join(os.path.dirname(__file__), 'keywordactive.html')
    self.response.out.write(template.render(path, template_values))

class twittercompare(webapp.RequestHandler):
  def get(self):
    query = self.request.get('q', '')
    width = self.request.get('w', '')
    height = self.request.get('h', '')
    method= self.request.get('m','')
    if not method:
      method='getkeywordactivity'
    if(not width):
      width='600';
    if not height:
      height='300';
    callback = self.request.get('callback', '')
    template_values = {
        'QUERY': query,
        'WIDTH': width,
        'HEIGHT': height,
        'METHOD':method
      }
    
    path = os.path.join(os.path.dirname(__file__), 'twittercompare.html')
    self.response.out.write(template.render(path, template_values))    
###############################################
# getbadge #######################
###############################################    
class getbadge(webapp.RequestHandler):
  def get(self):
    parameters = parse_qs(os.environ.get('QUERY_STRING', ''))
    if 'id' in parameters:
        userid = escape(parameters['id'][0])
    else:
        self.response.out.write("<b>id field is missing..</b>")
        return
    template_values = {
        'USERID': userid
      }

    path = os.path.join(os.path.dirname(__file__), 'badge.html')
    self.response.out.write(template.render(path, template_values))
class getfancybadge(webapp.RequestHandler):
  def get(self):
    parameters = parse_qs(os.environ.get('QUERY_STRING', ''))
    if 'id' in parameters:
        userid = escape(parameters['id'][0])
    else:
        self.response.out.write("<b>id field is missing..</b>")
        return
    template_values = {
        'USERID': userid,
        'IMAGE_SRC':get_profile_image_src(userid),
        'TweetActiveIndex':getactiveindex(userid)
      }

    path = os.path.join(os.path.dirname(__file__), 'fancybadge.html')
    self.response.out.write(template.render(path, template_values)) 
###############################################
# Serve RTKey website #######################
###############################################
class RealTimeKey(webapp.RequestHandler):
  def get(self):
    trendjson=gettrendlistjson();
    html='';
    for trend in trendjson['trends']:
        link_tag='<a style=\"text-decoration:none\" href=\"javascript:RealKeywordDisplay.ChangeQuery(\''+trend['name']+'\')\">';
        font_start_tag='<span>';
        tweet=trend['name'];
        html=html+link_tag+font_start_tag+tweet+"</span>"+"</a>&nbsp";
    query = self.request.get('q', '')
    if not query:
      self.response.out.write('query (q) is missing!!!!');
      return;
    template_values = {
        'oscars': query,
        'TRENDLIST':html,
        'TWEETS':get_realtweethtml(getkeywordjson(query))
      }
    path = os.path.join(os.path.dirname(__file__), 'rtkey.html')
    self.response.out.write(template.render(path, template_values))
###############################################
# Guestbook #######################
###############################################
class Guestbook(webapp.RequestHandler):
    def get(self):
        greetings_query = Greeting.all().order('-date')
        greetings = greetings_query.fetch(20)
        template_values = {
        'greetings': greetings
        }
        path = os.path.join(os.path.dirname(__file__), 'feedback.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        greeting = Greeting()
        greeting.content = self.request.get('content');
        greeting.author=self.request.get('name');
        greeting.put()
        self.redirect('/feedback')
class Tweetactiveindex(webapp.RequestHandler):
    def get(self):
        queries = self.request.get('q', '');
        alldata=[];
        i=10;
        if(not queries):
            self.response.out.write('q is missing.');
        query_array=queries.split(',');
        for query in query_array:
            index=getactiveindex(query)
            params={'data': [[i, index]],
				'label':query,
				'bars':
                { 'show': True,
                   'barWidth': 2,
                    'align': "center",
                }
                };
            alldata.append(params);
            i=i+10;
        jsonstr=simplejson.dumps(alldata);
        width = self.request.get('w', '')
        height = self.request.get('h', '')
        if(not width):
            width='600';
        if not height:
            height='300';
        template_values = {
        'GRAPHDATA': jsonstr,
        'WIDTH': width,
        'HEIGHT': height,
        };
        path = os.path.join(os.path.dirname(__file__), 'tweetactiveindex.html')
        self.response.out.write(template.render(path, template_values))
class Credits(webapp.RequestHandler):
    def get(self):
        template_values = {};
        path = os.path.join(os.path.dirname(__file__), 'credits.html')
        self.response.out.write(template.render(path, template_values))
class Gettrendlist(webapp.RequestHandler):
    def get(self):
        trendjson=gettrendlistjson();
        html='';
        for trend in trendjson['trends']:
            link_tag='<a style=\"text-decoration:none\" href=\"javascript:RealKeywordDisplay.ChangeQuery(\''+trend['name']+'\')\">';
            font_start_tag='<span>';
            tweet=trend['name'];
            html=html+link_tag+font_start_tag+tweet+"</span>"+"</a>&nbsp";
        self.response.out.write(html)
class Favicon(webapp.RequestHandler):
    def get(self):
        self.redirect('./images/favicon.ico')
class Robots(webapp.RequestHandler):
    def get(self):
        self.redirect('./static/robots.txt');
class Apple_icon(webapp.RequestHandler):
    def get(self):
        self.redirect('./images/logo.jpg');
class GetRealTweet(webapp.RequestHandler):
    def get(self):
        query = self.request.get('q', '')
        self.response.out.write(get_realtweethtml(getkeywordjson(query)));
def getTweetupData(query,self):
    template_values=memcache.get('GetTweetupData/'+query);
    if template_values is not None:
        template_values["TWEETS"]=get_realtweethtml(getkeywordjson(query))
        return template_values;
    if(not query):
        self.redirect('/tweetups')
        return None;
    results = db.GqlQuery("SELECT * FROM TweetUpDetail WHERE eventhandle = :1",query)
    db_tweetups=results.fetch(1);
    if(len(db_tweetups)==0):
        self.redirect('/tweetups')
        return None;
    else:
        tweetup=db_tweetups[0];
    tweople_query= db.GqlQuery("SELECT * FROM TweetUpPeople WHERE tweetup = :1",tweetup)
    tweople_list=tweople_query.fetch(200);
    rows=[];
    democracy={"location":{},"time":{}};
    tweetactive_url='http://www.tweetactive.com/tweetactiveindex?q=';
    for tweople in tweople_list:
        cc={"c":[]};
        try:
            cc={"c":[]};
            cc["c"].append({"v":tweople.user});
            cc["c"].append({"v":getuserinfojson(tweople.user)['followers_count']});
            cc["c"].append({"v":getuserinfojson(tweople.user)['friends_count']});
            cc["c"].append({"v":getactiveindex(tweople.user)});
            cc["c"].append({"v":tweople.location});
            cc["c"].append({"v":str(tweople.date)});
        except:
            cc={"c":[]};
            cc["c"].append({"v":tweople.user});
            cc["c"].append({"v":0});
            cc["c"].append({"v":0});
            cc["c"].append({"v":getactiveindex(tweople.user)});
            cc["c"].append({"v":tweople.location});
            cc["c"].append({"v":str(tweople.date)});
        tweetactive_url=tweetactive_url+tweople.user+',';
        rows.append(cc);
        democracy["location"][tweople.location]=0;
        democracy["time"][tweople.date]=0;
    for tweople in tweople_list:
        democracy["location"][tweople.location]=democracy["location"][tweople.location]+1;
        democracy["time"][tweople.date]=democracy["time"][tweople.date]+1;
    max_date_vote=0;
    max_date=None;
    for datekey in democracy["time"].keys():
        if(max_date_vote<democracy["time"][datekey]):
            max_date_vote=democracy["time"][datekey];
            max_date=datekey;
    max_loc_vote=0;
    max_loc="";
    for lockey in democracy["location"].keys():
        if(max_loc_vote<democracy["location"][lockey]):
            max_loc_vote=democracy["location"][lockey];
            max_loc=lockey;
    if max_date:
        tweetup.date=max_date;#maximum voted date, not most latest or something
    if max_loc:
        tweetup.location=max_loc;
    tweople_rows=simplejson.dumps(rows);
    tweetactive_url=tweetactive_url[:len(tweetactive_url)-1];
    template_values = {
    'TWEETS': get_realtweethtml(getkeywordjson(query)),
    'QUERY':query,
    'TWEETUP':tweetup,
    'ROWS':tweople_rows,
    'MAX_VOTE_TIME':max_date_vote,
    "TWEETACTIVEINDEXURL":tweetactive_url,
    'MAX_VOTE_LOC':max_loc_vote
    };
    memcache.add('GetTweetupData/'+query, template_values, 1800);
    return template_values;
class Tweetup(webapp.RequestHandler):
    def get(self):
        query = self.request.get('q', '');
        template_values=getTweetupData(query,self);
        path = os.path.join(os.path.dirname(__file__), 'hydtweetup.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        tag =self.request.get('tag');
        if(not tag):
            self.redirect('/tweetups')
            return;
        results = db.GqlQuery("SELECT * FROM TweetUpDetail WHERE eventhandle = :1",tag)
        db_tweetups=results.fetch(1);
        if(len(db_tweetups)==0):
            self.redirect('/tweetups')
            return;
        tweetup=db_tweetups[0];
        #look for people now!!!
        tweople_query= db.GqlQuery("SELECT * FROM TweetUpPeople WHERE user = :1 AND tweetup=:2",self.request.get('twitteruserid'),tweetup);
        tweople_list=tweople_query.fetch(1)
        if(len(tweople_list)==0):
            tweople=TweetUpPeople();
        else:
            tweople=tweople_list[0];
        tweople.tweetup=tweetup.key();
        tweople.user = self.request.get('twitteruserid');
        tweople.location=self.request.get('locationpref');
        mydate=self.request.get('datepref')+' '+self.request.get('timepref');
        mytime=time.strptime(mydate,'%m/%d/%Y %H');
        finaldate=datetime(*mytime[0:5]);
        tweople.date=finaldate;
        tweople.put()
        memcache.delete('GetTweetupData/'+tag);
        self.redirect('/tweetup?q='+tag);
class TweetupStart(webapp.RequestHandler):
    def get(self):
        tweetups_query = TweetUpDetail.all().order('-date')
        tweetups = tweetups_query.fetch(100)
        template_values = {
        'TWEETUPDATA': tweetups
        }
        path = os.path.join(os.path.dirname(__file__), 'tweetups.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        results = db.GqlQuery("SELECT * FROM TweetUpDetail WHERE eventhandle = :1",self.request.get('tag'))
        db_tweetups=results.fetch(1);
        if(len(db_tweetups)==0):
            tweetup=TweetUpDetail();
        else:
            tweetup=db_tweetups[0];
        tweetup.eventhandle = self.request.get('tag');
        tweetup.description=self.request.get('description');
        mytime=time.strptime(self.request.get('datetime'),'%Y/%m/%d %H:%M');
        tweetup.date=datetime(*mytime[0:5]);
        tweetup.location=self.request.get('location');
        tweetup.put()
        self.redirect('/tweetups')
class MemDelete(webapp.RequestHandler):
    def get(self):
        memcache.flush_all();
        self.response.out.write('Done!!!!');
class Temp(webapp.RequestHandler):
    def get(self):
        template_values = {};
        path = os.path.join(os.path.dirname(__file__), 'hydtweetuptemp.html')
        self.response.out.write(template.render(path, template_values))
class CheatSheat(webapp.RequestHandler):
    def get(self):
        query = self.request.get('q', '');
        if(not query):
            self.redirect('/tweetups')
            return
        results = db.GqlQuery("SELECT * FROM TweetUpDetail WHERE eventhandle = :1",query)
        db_tweetups=results.fetch(1);
        if(len(db_tweetups)==0):
            self.redirect('/tweetups')
            return;
        else:
            tweetup=db_tweetups[0];
        tweople_query= db.GqlQuery("SELECT * FROM TweetUpPeople WHERE tweetup = :1",tweetup)
        tweople_list=tweople_query.fetch(200);
        ta_tweople_list=[];
        for tweople in tweople_list:
            try:
                tw=taTweople();
                tw.handle=tweople.user;
                tw.follower_count=getuserinfojson(tweople.user)['followers_count'];
                tw.friend_count=getuserinfojson(tweople.user)['friends_count'];
                tw.picurl=getuserinfojson(tweople.user)['profile_image_url'];
                tw.name=getuserinfojson(tweople.user)['name'];
                tw.bio=getuserinfojson(tweople.user)['description'];
                ta_tweople_list.append(tw);
            except:
                a=1;
        template_values = {
            "LIST":ta_tweople_list
        };
        path = os.path.join(os.path.dirname(__file__), 'tweetupcheatsheet.html')
        self.response.out.write(template.render(path, template_values))
def main():
  application = webapp.WSGIApplication(
                                       [('/', MainPage),
                                        ('/getbadge',getbadge),
                                        ('/profileimage',profileimage),
                                        ('/friends',friends),
                                        ('/followers',followers),
                                        ('/getactivity',getactivity),
                                        ('/getfancybadge',getfancybadge),
                                        ('/keywordactive',keywordactive),
                                        ('/twittercompare',twittercompare),
                                        ('/getkeywordactivity',getkeywordactivity),
                                        ('/gettwitterlove',gettwitterlove),
                                        ('/rtkey',RealTimeKey),
                                        ('/feedback',Guestbook),
                                        ('/tweetactiveindex',Tweetactiveindex),
                                        ('/credits',Credits),
                                        ('/gettrendlist',Gettrendlist),
                                        ('/favicon.ico',Favicon),
                                        ('/robots.txt',Robots),
                                        ('/apple-touch-icon.png',Apple_icon),
                                        ('/getrealtweet',GetRealTweet),
                                        ('/tweetup',Tweetup),
                                        ('/tweetups',TweetupStart),
                                        ('/flushmemcache',MemDelete),
                                        ('/hydtweetupvenue',Temp),
                                        ('/cheatsheet',CheatSheat)
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
